package com.zzyl.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class WechatServiceImpl implements WechatService {

    private static final String GET_OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private static final String GET_PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    private static final String GET_ACCESSTOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";

    @Value("${zzyl.framework.wechat.appId}")
    private String appid;
    @Value("${zzyl.framework.wechat.secret}")
    private String secret;


    @Override
    public String getOpenid(String code) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("js_code", code);
        map.put("appid", appid);
        map.put("secret", secret);
        String jsonStr = HttpUtil.get(GET_OPENID_URL, map);
        JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
        if (jsonObject.getInt("errcode") != null) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }

        return jsonObject.getStr("openid");
    }

    @Override
    public String getPhone(String code) {
        HashMap<String, Object> map = new HashMap<>();
        String accessToken = getAccessToken();
        String url = GET_PHONE_URL + accessToken;
        map.put("code", code);
        String jsonStr = HttpUtil.post(url,JSONUtil.toJsonStr(map) );
        JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
        if (jsonObject.getInt("errcode") != 0) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        JSONObject phoneInfo = jsonObject.getJSONObject("phone_info");
        return phoneInfo.getStr("phoneNumber");
    }


    public String getAccessToken() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("grant_type", "client_credential");
        map.put("appid", appid);
        map.put("secret", secret);
        String jsonStr = HttpUtil.get(GET_ACCESSTOKEN_URL, map);
        JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
        if (jsonObject.getInt("errcode") != null) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getStr("access_token");
    }
}
